<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\RemoteApiRoute;
use App\Http\Controllers\Controller;
use App\Models\WtCategory;
use App\Models\WtLowOrder;
use App\Models\WtOrderAsin;
use App\Models\WtOrderProduct;
use App\Models\WtTask;
use App\Services\Admin\AdminService;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use MongoDB\BSON\ObjectId;
use function Symfony\Component\String\s;

class HomeController extends Controller
{
    protected $request;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(Request $request)
    {
        set_time_limit(60);
        $this->request = $request;
    }

    /**
     * 用户注册
     * @param AdminService $adminService
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function register(AdminService $adminService)
    {
        $this->validate($this->request, [
            'username' => 'required|unique:wt_admin',
            'email' => 'required|email',
            'password' => 'required|min:6|max:255'
        ]);

        $result = $adminService->register($this->request->post());
        return $result;
    }

    /**
     * 用户登录
     * @param AdminService $adminService
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(AdminService $adminService)
    {
        $this->validate($this->request, [
            'username' => 'required',
            'password' => 'required|min:6|max:255'
        ]);

        $result = $adminService->login($this->request->post());
        return $result;
    }

    public function get_asin_order_num()
    {
        $url = env('REMOTE_API_URL') . RemoteApiRoute::ASIN_ORDER_NUM;
        $post = $this->request->post();
        $response = Http::get($url, $post);

        if ($response->ok()) {
            return $response->json();
        } else {
            return Error('okk');
        }
    }

    /**
     * 获取崇伍所有项目组
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_wt_group()
    {

        $url = env('REMOTE_API_URL') . RemoteApiRoute::ALL_GROUPS;
        $post = $this->request->post();
        $response = Http::get($url, $post);

        if ($response->ok()) {
            return $response->json();
        } else {
            return Error('okk');
        }
    }

    /**
     * 生成分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generate_category(Request $request)
    {
        $post = $request->post();
        if (!$post['month']) {
            return Error('未知的月份！');
        }

        //检测是否正在生成中
        $is_ing = WtTask::where('category_completed', 'pending')->orWhere('order_product_completed', 'pending')->orWhere('update_sj_name_extra_completed', 'pending')->orWhere('update_category_completed', 'pending')->orWhere('low_orders_completed', 'pending')->first();
        if ($is_ing) {
            return Error($is_ing->month . '月的数据正在生成中！');
        }

        //检测是否为2024-04月之前的历史数据生成
        $month = $post['month'];
        if (strtotime($month) < strtotime('2024-04')) {
            $exists = WtCategory::where(['month' => $month])->first();
            if ($exists) {
                print_r('已存在该月份数据！');
                exit();
            }

            ini_set('memory_limit', '1024M');
            $categories = WtCategory::where(['month' => '2024-04'])->get();
            $inserts = [];
            foreach ($categories as $category) {
                $inserts[] = [
                    'catId' => $category->catId,
                    'domainId' => $category->domainId,
                    'name' => $category->name,
                    'parent_id' => $category->parent_id,
                    'month' => $month,
                    'children_str' => $category->children_str,
                    'children_num' => $category->children_num,
                ];
            }
            $re = WtCategory::insert($inserts);
            WtTask::where('month', $month)->update(['category_completed' => 'completed', 'completed' => 'pending']);
            return Success('生产完毕！', $re);
        } else {
            //调用python请求keepa分类
            $pythonScriptPath = 'wt_category.py';

            // 使用 popen 启动 Python 脚本，'&' 将其放到后台执行
            pclose(popen("nohup python {$pythonScriptPath} {$month} > /dev/null 2>&1 &", 'r'));
            return Success('分类抓取中，请耐心等待...', $month);
        }
    }

    /**
     * 请求ceping_system生成订单asin数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generate_order_asin(Request $request)
    {
        //该月是否已生成
        $post = $request->post();
        $where['month'] = $post['month'];
        $exists = WtOrderAsin::where($where)->first();
        if ($exists) {
            return Error('该月已生成asin订单数据');
        }

        //上一步是否完成
        $static = WtTask::where('month', $post['month'])->first();
        if ($static->category_completed !== 'completed') {
            return Error('本月分类数据尚未获取完毕！');
        }

        //请求ceping的订单数据
        $url = env('REMOTE_API_URL') . RemoteApiRoute::ASIN_ORDER_NUM;
        $response = Http::get($url, $post);
        if ($response->ok()) {
            if ($response->json()['status']) {
                $insert = array();
                $res = $response->json()['result'];
                foreach ($res as $re) {
                    if (isset($re['_id']['asin'])) {
                        $insert[] = [
                            'month' => $post['month'],
                            'country' => strtolower($re['_id']['country']),
                            'asin' => $re['_id']['asin'],
                            'order_num' => $re['counts'],
                            'order_counts' => $re['quantities'],
                            'sku_count' => $re['sku_count'],
                            'group_name' => $re['_id']['group_name'],
                        ];
                    }
                }

                if (count($insert)) {
                    ini_set('memory_limit', '1024M');
                    $ret = WtOrderAsin::insert($insert);
                    WtTask::where('month', $post['month'])->update(['order_asin_completed' => 'completed']);
                    return Success('获取成功', $ret);

                } else {
                    return Error('该月无asin订单数据');
                }
            } else {
                return Error($response->json()['message']);
            }

        } else {
            return Error('请求失败');
        }
    }

    /**
     * 获取订单产品Keepa详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generate_order_product(Request $request)
    {
        $post = $request->post();
        if (!$post['month']) {
            return Error('未知的月份！');
        }

        //检测是否正在生成中
        $is_ing = WtTask::where('category_completed', 'pending')->orWhere('order_product_completed', 'pending')->orWhere('update_sj_name_extra_completed', 'pending')->orWhere('update_category_completed', 'pending')->orWhere('low_orders_completed', 'pending')->first();
        if ($is_ing) {
            return Error($is_ing->month . '月的数据正在生成中！');
        }

        //检查上一步是否完成
        $last_step = WtTask::where('month', $post['month'])->first();
        if ($last_step->order_asin_completed !== 'completed' && $last_step->order_product_completed !== 'wait') {
            return Error('订单asin尚未获取，请按照步骤获取数据！');
        }

        $month = $post['month'];
        $pythonScriptPath = 'wt_order_product_local.py';
        // 使用 popen 启动 Python 脚本，'&' 将其放到后台执行
        pclose(popen("nohup python {$pythonScriptPath} {$month} > /dev/null 2>&1 &", 'r'));
        return Success('产品抓取中，请耐心等待...', $last_step);
    }

    /**
     * 更新产品表中数据名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generate_sj_name(Request $request)
    {
        //该月是否已生成
        $post = $request->post();
        $month = $post['month'];

        //上一步是否完成
        $static = WtTask::where('month', $month)->first();
        if ($static->order_product_completed !== 'completed') {
            return Error('本月产品数据尚未获取完毕！');
        }

        ini_set('memory_limit', '1024M');
        $url = env('REMOTE_API_URL') . RemoteApiRoute::ASIN_SJ_NAME;
        $response = Http::get($url);
        if ($response->ok()) {
            $sj_names = $response->json()['data'];
            $bulkUpdates = [];
            foreach ($sj_names as $k => $v) {
                $bulkUpdates[] = [
                    'updateMany' => [
                        ['asin' => $k, 'month' => $month, 'sj_name' => ['$exists' => false]],
                        ['$set' => ['sj_name' => $v]],
                        ['upsert' => false]
                    ]
                ];
            }

            if (count($bulkUpdates)) {
                WtOrderProduct::raw(function ($collection) use ($bulkUpdates) {
                    $collection->bulkWrite($bulkUpdates);
                });
                $ret = WtTask::where('month', $month)->update(['update_sj_name_completed' => 'completed']);
                return Success('成功', $ret);
            } else {
                return Success('暂无需要更新的数据');
            }
        } else {
            return Error($response->reason());
        }
    }

    /**
     * 更新产品表中数据名-python
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generate_python_sj(Request $request)
    {
        $post = $request->post();
        if (!$post['month']) {
            return Error('未知的月份！');
        }

        //检测是否正在生成中
        $is_ing = WtTask::where('category_completed', 'pending')->orWhere('order_product_completed', 'pending')->orWhere('update_sj_name_extra_completed', 'pending')->orWhere('update_category_completed', 'pending')->orWhere('low_orders_completed', 'pending')->first();
        if ($is_ing) {
            return Error($is_ing->month . '月的数据正在生成中！');
        }

        //检查上一步是否完成
        $last_step = WtTask::where('month', $post['month'])->first();
        if ($last_step->update_sj_name_completed !== 'completed') {
            return Error('数据名尚未更新，请按照步骤获取数据！');
        }

        $month = $post['month'];
        $pythonScriptPath = 'wt_sj_name.py';
        // 使用 popen 启动 Python 脚本，'&' 将其放到后台执行
        pclose(popen("nohup python {$pythonScriptPath} {$month} > /dev/null 2>&1 &", 'r'));
        return Success('数据名更新中，请耐心等待...', $last_step);
    }

    /**
     * 更新分类表中订单量等数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generate_order_num(Request $request)
    {
        $post = $request->post();
        if (!$post['month']) {
            return Error('未知的月份！');
        }

        //检测是否正在生成中
        $is_ing = WtTask::where('category_completed', 'pending')->orWhere('order_product_completed', 'pending')->orWhere('update_sj_name_extra_completed', 'pending')->orWhere('update_category_completed', 'pending')->orWhere('low_orders_completed', 'pending')->first();
        if ($is_ing) {
            return Error($is_ing->month . '月的数据正在生成中！');
        }

        //检查上一步是否完成
        $last_step = WtTask::where('month', $post['month'])->first();
        if ($last_step->update_sj_name_extra_completed !== 'completed') {
            return Error('数据名(python)尚未更新，请按照步骤获取数据！');
        }
        $month = $post['month'];
        $pythonScriptPath = 'wt_category_update.py';

        // 使用 popen 启动 Python 脚本，'&' 将其放到后台执行
        pclose(popen("nohup python {$pythonScriptPath} {$month} > /dev/null 2>&1 &", 'r'));
        return Success('订单量等信息更新中，请耐心等待...');
    }

    /**
     * 生成低订单分析数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generate_low_order(Request $request)
    {
        $post = $request->post();
        $low_type = $post['low_type'];
        if (!$post['month']) {
            return Error('未知的月份！');
        }

        //检测是否正在生成中
        $is_ing = WtTask::where('category_completed', 'pending')->orWhere('order_product_completed', 'pending')->orWhere('update_sj_name_extra_completed', 'pending')->orWhere('update_category_completed', 'pending')->orWhere('low_orders_completed', 'pending')->first();
        if ($is_ing) {
            return Error($is_ing->month . '月的数据正在生成中！');
        }

        //检查上一步是否完成
        $last_step = WtTask::where('month', $post['month'])->first();
        if ($last_step->update_category_completed !== 'completed') {
//            return Error('订单量更新至分类树尚未完成，请按照步骤获取数据！');
        }

        //低订单四步
        $steps = ['wt_low_order', 'update_low', 'update_current_month', 'update_last_two_month'];
        $step_key = array_search($post['low_type'], $steps);
        if ((int)$step_key > 0){
            $low_step_key = $steps[$step_key-1];
            $low_step = $last_step->low_orders_completed[$low_step_key];

            if ((int)$low_step['value'] == 0){
                return Error('低订单上一步（'.$steps[$step_key-1].'）尚未完成，请按照步骤获取数据！');
            }
        }

        $month = $post['month'];
        $pythonScriptPath = base_path('app/PythonScripts/'.$post['low_type'].'.py'); // 脚本的完整路径

        // 使用 popen 启动 Python 脚本，'&' 将其放到后台执行
        pclose(popen("nohup python {$pythonScriptPath} {$month} > /dev/null 2>&1 &", 'r'));
        return Success('低订单数据生成中，请耐心等待...');
    }

    /**
     * 获取低订单列表-旧
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_low_order_bak(Request $request)
    {
        $params = $request->post();
        $where = array();

        //筛选条件
        $pageSize = $params['pageSize'];
        $page = $params['page'];
        $skip = $pageSize * ($page - 1);

        //获取前两个月
        $months = get_last_two_month($params['month']);
        $where['month'] = ['$in' => $months];
        $where['country_desc'] = $params['country'];
        if ($params['group_name']) {
            $where['group_name'] = $params['group_name'];
        }
        if ($params['is_limit'] !== '') {
            if ((int)$params['is_limit']) {
                $where['is_human'] = 1;
            } else {
                $where['is_human'] = ['$ne' => 1];
            }
        }
        if ($params['limit_type'] !== '') {
            $where['limit_type'] = (int)$params['limit_type'];
        }

        //查询在售状态
        $status = ['$in' => ['在售', '不在售']];
        if ($params['status'] !== '') {
            $status = $params['status'];
        }

        $count_where = $where;
        $count_where['order_num'] = ['$lte' => (int)$params['month_num']];

        $total = WtLowOrder::where($count_where)->count();
        $pipeline = [
            [
                '$match' => $where
            ],
            [
                '$group' => [
                    '_id' => [
                        'asin' => '$asin',
                        'group_name' => '$group_name',
                        'country_desc' => '$country_desc',
                        'month' => '$month',
                    ],
                    'limit_type' => ['$first' => '$limit_type'],
                    'limit_reason' => ['$first' => '$limit_reason'],
                    'nickname' => ['$first' => '$nickname'],
                    'limit_time' => ['$first' => '$limit_time'],
                    'order_num' => ['$sum' => '$order_num'],
                    'status' => ['$first' => '$status'],
                    'title' => ['$first' => '$title'],
                    'image' => ['$first' => '$image'],
                    'has_moved' => ['$first' => '$has_moved'],
                    'categories_tree' => ['$first' => '$categories_tree'],
                ]
            ],
            [
                '$addFields' => [
                    'current_month_order_num' => [
                        '$cond' => [
                            ['$eq' => ['$_id.month', $months[0]]], //当前搜索月份
                            '$order_num',
                            0
                        ]
                    ],
                    'current_month_status' => [
                        '$cond' => [
                            ['$eq' => ['$_id.month', $months[0]]], //当前搜索月份
                            '$status',
                            '在售'
                        ]
                    ],
                ]
            ],
            [
                '$group' => [
                    '_id' => [
                        'asin' => '$_id.asin',
                        'group_name' => '$_id.group_name',
                        'country_desc' => '$_id.country_desc',
                    ],
                    'current_month_order_num' => ['$sum' => '$current_month_order_num'],
                    'current_month_status' => ['$first' => '$current_month_status'],
                    'limit_type' => ['$first' => '$limit_type'],
                    'limit_reason' => ['$first' => '$limit_reason'],
                    'nickname' => ['$first' => '$nickname'],
                    'limit_time' => ['$first' => '$limit_time'],
                    'status' => ['$first' => '$status'],
                    'has_moved' => ['$first' => '$has_moved'],
                    'title' => ['$first' => '$title'],
                    'image' => ['$first' => '$image'],
                    'categories_tree' => ['$first' => '$categories_tree'],
                    'months' => [
                        '$push' => [
                            'month' => '$_id.month',
                            'group_name' => '$_id.group_name',
                            'country_desc' => '$_id.country_desc',
                            'order_num' => '$order_num',
                        ]
                    ],
                ],
            ],
            [
                '$project' => [
                    'asin' => '$_id.asin',
                    'group_name' => '$_id.group_name',
                    'country_desc' => '$_id.country_desc',
                    'current_month_order_num' => '$current_month_order_num',
                    'current_month_status' => '$current_month_status',
                    'limit_type' => '$limit_type',
                    'limit_reason' => '$limit_reason',
                    'nickname' => '$nickname',
                    'limit_time' => '$limit_time',
                    'has_moved' => '$has_moved',
                    'status' => '$status',
                    'title' => '$title',
                    'image' => '$image',
                    'categories_tree' => '$categories_tree',
                    'monthly_orders' => [
                        '$arrayToObject' => [
                            '$map' => [
                                'input' => '$months',
                                'as' => 'monthData',
                                'in' => [
                                    'k' => '$$monthData.month',
                                    'v' => '$$monthData.order_num'
                                ]
                            ]
                        ]
                    ]
                ]
            ],
            [
                '$match' => [
                    'current_month_order_num' => ['$lte' => (int)$params['month_num']],
                    'current_month_status' => $status
                ]
            ],
            [
                '$sort' => [
                    'current_month_order_num' => -1,
                    'asin' => -1,
                    'country_desc' => -1,
                    'group_name' => -1,
                ]
            ],
            [
                '$skip' => $skip
            ],
            [
                '$limit' => $pageSize
            ],
        ];

        // 执行聚合查询，并设置 allowDiskUse 选项
        $orders = WtLowOrder::raw(function ($collection) use ($pipeline) {
            return $collection->aggregate($pipeline, ['allowDiskUse' => true]);
        });
        foreach ($orders as $order) {
            $order->limit_type_desc = get_limit_type($order->limit_type);
            $order->month = $params['month'];
            $order->current = isset($order['monthly_orders'][$months[0]]) ? $order['monthly_orders'][$months[0]] : 0;
            $order->last = isset($order['monthly_orders'][$months[1]]) ? $order['monthly_orders'][$months[1]] : 0;
            $order->last_last = isset($order['monthly_orders'][$months[2]]) ? $order['monthly_orders'][$months[2]] : 0;
            $order->limit_time = $order->limit_time ? date('Y-m-d H:i', $order->limit_time) : '';
        }
        return Success('ok', ['items' => $orders, 'total' => $total, 'where' => $where]);
    }

    /**
     * 获取低订单列表-新
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_low_order(Request $request)
    {
        $params = $request->post();
        $where = array();

        //分页
        $pageSize = $params['pageSize'];
        $page = $params['page'];
        $skip = $pageSize * ($page - 1);

        //筛选条件
        $where['month'] = $params['month'];
        $where['country_desc'] = $params['country'];
        if ($params['group_name']) {
            $where['group_name'] = $params['group_name'];
        }
        if (isset($params['asin']) && $params['asin'] !== '') {
            $where['asin'] = trim($params['asin']);
        }
        if ($params['is_limit'] !== '') {
            if ((int)$params['is_limit']) {
                $where['is_human'] = 1;
            } else {
                $where['is_human'] = ['$ne' => 1];
            }
        }
        if ($params['limit_type'] !== '') {
            $where['limit_type'] = (int)$params['limit_type'];
        }

        //查询在售状态
        if ($params['status'] !== '') {
            $where['status'] = $params['status'];
        }
        $where['order_num'] = ['$lte' => (int)$params['month_num']];

        $total = WtLowOrder::where($where)->count();
        $orders = WtLowOrder::where($where)->skip($skip)->limit($pageSize)->orderBy('order_num', 'desc')->get();

        //整理数据
        foreach ($orders as $order) {
            $order->limit_type_desc = get_limit_type($order->limit_type);
            $order->limit_time = $order->limit_time ? date('Y-m-d H:i', $order->limit_time) : '';
            $order->current = $order->order_num;
        }

        return Success('ok', ['items' => $orders, 'total' => $total]);
    }

    /**
     * 校验asin是否已被限制
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function check_asin_is_limit(Request $request)
    {
        $url = env('REMOTE_API_URL') . RemoteApiRoute::CHECK_ASIN_IS_LIMIT;
        $response = Http::get($url, $request->post());
        if ($response->ok()) {
            $data = $response->json();
            return Success($data['message'], $data['result']);
        } else {
            return Error($response->reason());
        }
    }

    /**
     * 获取所有限制类型
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_all_limit_type()
    {
        $url = env('REMOTE_API_URL') . RemoteApiRoute::GET_ALL_LIMIT_TYPE;
        $response = Http::get($url);
        if ($response->ok()) {
            $data = $response->json();
            return Success($data['message'], $data['result']);
        } else {
            return Error($response->reason());
        }
    }

    public function set_asin_limit_remote(Request $request)
    {
        // 创建 GuzzleHttp 客户端实例
        $params = $request->post();
        $client = new Client();

        // 设置你要发送 POST 请求的 URL
        $url = env('REMOTE_API_URL') . RemoteApiRoute::SET_ASIN_LIMIT;

        $response = $client->request('POST', $url, [
            'form_params' => $params
        ]);

        // 获取响应体内容
        $responseBody = $response->getBody()->getContents();
        $json = json_decode($responseBody, true);

        if ($json['code'] == 0) {
            return Success($json['message'], $json['result']);
        } else {
            return Error($json['message']);
        }
    }

    /**
     * 设置asin限制采购
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function set_asin_limit(Request $request)
    {
        $params = $request->post();
        $user_id = $request->get('currentUserId');
        $adminServe = new AdminService();
        $user = $adminServe->getUserInfo($user_id);

        $where = [
            'group_name' => $params['group_name'],
            'country_desc' => $params['country_desc'],
            'asin' => $params['asin'],
            'month' => $params['month'],
        ];
        if (!isset($params['limit_reason'])) {
            $params['limit_reason'] = '';
        }

        $result = WtLowOrder::where($where)->update(['$set' => [
            'limit_type' => $params['limit_type'],
            'user_id' => $user->id,
            'nickname' => $user->nickname,
            'limit_time' => time(),
            'is_human' => 1,
            'limit_reason' => $params['limit_reason']
        ], '$unset' => [
            'has_moved' => '' // 删除has_moved字段
        ]]);
        if ($result) {
            return Success('限制成功！', $params);
        } else {
            return Error('限制失败，请稍后重试！');
        }
    }

    /**
     * 设置asin限制采购
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function set_group_limit(Request $request)
    {
        $params = $request->post();
        $user_id = $request->get('currentUserId');
        $adminServe = new AdminService();
        $user = $adminServe->getUserInfo($user_id);
        $time = time();
        if (!isset($params['limit_reason'])) {
            $params['limit_reason'] = '';
        }

        if (!isset($params['where']) || !count($params['where']['ids'])) {
            return Error('批量限制失败，请勾选要批量限制的记录！');
        }
        $filter = $params['where'];
        $ids = $filter['ids'];

        //转为对象
        foreach ($ids as $id){
            $id_arr[] = new ObjectId($id);
        }
        $where = [
            '_id' => ['$in' => $id_arr],
            'month' => $filter['month']
        ];
        WtLowOrder::where($where)->update(['$set' => [
            'limit_type' => $params['limit_type'],
            'limit_reason' => $params['limit_reason'],
            'user_id' => $user->id,
            'is_human' => 1,
            'nickname' => $user->nickname,
            'limit_time' => $time
        ], '$unset' => [
            'has_moved' => '' // 删除has_moved字段
        ]]);
        return Success('限制成功！', $where);
    }

    /**
     * 将限制asin同步到测评系统
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sync_asin_to_system(Request $request)
    {
        $post = $request->post();
        if (!$post['month']) {
            return Error('未知的月份！');
        }

        //检测是否正在生成中
        $is_ing = WtTask::where('category_completed', 'pending')->orWhere('order_product_completed', 'pending')->orWhere('update_sj_name_extra_completed', 'pending')->orWhere('update_category_completed', 'pending')->orWhere('low_orders_completed', 'pending')->first();
        if ($is_ing) {
            return Error($is_ing->month . '月的数据正在生成中！');
        }

        //检查上一步是否完成
        $last_step = WtTask::where('month', $post['month'])->first();
        if ((int)$last_step->low_orders_completed['update_last_two_month']['value'] !== 1) {
            return Error('低订单尚未完成，请按照步骤操作！'.$last_step->low_orders_completed['update_last_two_month']['value']);
        }

        $month = $post['month'];
        $pythonScriptPath = base_path('app/PythonScripts/move_to_system.py'); // 脚本的完整路径

        // 使用 popen 启动 Python 脚本，'&' 将其放到后台执行
        pclose(popen("nohup python {$pythonScriptPath} {$month} > /dev/null 2>&1 &", 'r'));
        return Success('低订单asin同步系统中，请耐心等待...');
    }
}
